#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
import time
import sys
from threading import Thread
import getopt
from networking import *

#default arguments:
SERVER=False
IP='127.0.0.1'
PORT=23456

def usage():
    print 'Usage: '+os.path.basename(sys.argv[0])+'[OPTIONS]'
    print '-h, --help: Display this help message.'
    print '-s, --server: Run as server. (default: Run as client)'
    print '-i, --ip: Server IP address (default: '+IP+')'
    print '-p, --port: Port number (default: '+str(PORT)+')'

def main():
    global SERVER,IP,PORT
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hsi:p:", ["help","server","ip=","port="])
    except getopt.GetoptError, err:
        # print help information and exit:
        print str(err) # will print something like "option -a not recognized"
        usage()
        sys.exit(2)
    for o, a in opts:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-s", "--server"):
            SERVER=True
        elif o in ("-i", "--ip"):
            IP=a
        elif o in ("-p", "--port"):
            PORT=a
        else:
            assert False, "unhandled option"

    print "SERVER=",SERVER
    print "IP=",IP
    print "PORT=",PORT
    
    if SERVER:
        CS=ChatServer(IP,PORT)
        GS=GameServer(IP,PORT)
        CS.start()
        GS.start()

    CC=ChatClient(IP,PORT)
    GC=GameClient(IP,PORT)
    CC.start()
    GC.start()

if __name__ == "__main__":
    main()
